const db = require("../../db/sql");
const {postDao} = require("../../DAO/postData");

async function addUser(params, res) {
    const {nick_name, sex, role, department, phone, userId, pwd} = params;
    if (role == '系统管理员') {
        res.sendStatus(409)
        return 0
    }
    const sql = 'INSERT INTO userlist SET ?';
    const newUser = {
        nick_name,
        sex,
        role,
        department,
        phone,
        userId,
        pwd
    };
    let isExist = false
    await db.query(`select * from userlist where userId = ${userId}`, (err, res) => {
        if (err) {
            console.log(err)
            throw err
        }
        if (res.length > 0) {
            isExist = true
        }
    })
    if (isExist) {
        res.status(303).send({
            msg: '该账户已添加,请更换账号后重新添加'
        })
        return
    }
    await db.query(sql, newUser, (error, results) => {
        if (error) {
            console.error(error);
            res.status(500).send({
                error: '服务器内部错误'
            });
        } else {
            res.status(200).send({
                message: '用户信息已成功添加',
                id: results.insertId
            });
        }
    });
}

module.exports = {
    addUser
}
